import 'dart:convert';

import 'package:meePet/utils/ext/IntExt.dart';
import 'package:meePet/utils/ext/StringExt.dart';

import '../app/Constants.dart';
import '../bean/ValityKeyData.dart';
import '../net/RequestManager.dart';
import '../utils/AesEcbPkcs7Util.dart';
import '../utils/LogUtils.dart';
import '../utils/SPUtil.dart';

class EncryptManager {
  static EncryptManager? _instance;
  String? _vitaSoy;

  static EncryptManager getInstance() {
    _instance ??= EncryptManager();
    return _instance!;
  }

  void init() {
    _vitaSoy = SPUtil.load(Constants.keyDesKey);
    _updateKey();
  }

  ///加密
  String getEncryptData(String content) {
    if (_vitaSoy == null) {
      _updateKey();
      return "";
    } else {
      return AesEcbPkcs7Util.encrypt(content, _vitaSoy!);
    }
  }

  ///解密
  String getDecrypt(String content) {
    if (_vitaSoy == null) {
      _updateKey();
      return content;
    } else {
      return AesEcbPkcs7Util.decrypt(content, _vitaSoy!);
    }
  }

  ///更新并保存key
  void _updateKey() {
    RequestManager.getUserClient()
        .getVitasoy()
        .then((value) => {_dealWithKey(value)});
  }

  void _dealWithKey(ValityKeyData data) {
    if (data.code != null && data.code!.isHttpSuccess() == true) {
      String jsonStr = json.encode(data.data);
      LogUtils.i("获取的key数据是:$jsonStr");

      String realKey = "";
      if (data.data != null && data.data!.cardId != null) {
        realKey = data.data!.cardId.toString().reversed();
      }
      LogUtils.i("获取realKey:$realKey");

      LogUtils.i("保存到sp:$realKey");
      _vitaSoy = realKey;
      SPUtil.save(Constants.keyDesKey, realKey);
    }
  }
}
